package com.lu.statistics.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lu.statistics.common.utils.DateUtils;
import com.lu.statistics.entity.RCustomer;
import com.lu.statistics.entity.SysDictItem;
import com.lu.statistics.entity.enums.CustomerStatusEnum;
import com.lu.statistics.loader.DataLoader;
import com.lu.statistics.mapper.RCustomerMapper;
import com.lu.statistics.mapper.SysDictItemMapper;
import com.lu.statistics.service.RCustomerService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


/**
 * 客户管理--RCustomerServiceImpl
 */
@Service
public class RCustomerServiceImpl extends ServiceImpl<RCustomerMapper, RCustomer> implements RCustomerService {
    @Autowired
    private RCustomerMapper customerMapper;
    @Autowired
    private SysDictItemMapper dictItemMapper;


    /**
     * 添加和修改用户信息
     *
     * @param customer
     * @return
     */
    @Override
    public void saveOrUpdateCustomer(RCustomer customer) {
        //查询字典名称名称
        SysDictItem item = dictItemMapper.queryDictItem("BOOKING_ROOM", customer.getBookingRoom());
        customer.setRoomName(item.getItemName());
        SysDictItem typeItem = dictItemMapper.queryDictItem("BOOKING_TYPE", customer.getBookingType());
        //获取酒席的开启时间
        Date startTime = this.getStartTime(customer.getBookingRoom(), customer.getStartTime());
        String value = DataLoader.getConfigValue("MEAL_DURATION");
        customer.setMealDuration(Integer.parseInt(value));
        Date endTime = this.getEndTime(startTime, customer.getMealDuration());
        customer.setStartTime(startTime);
        customer.setEndTime(endTime);
        customer.setTypeName(typeItem.getItemName());
        if (customer.getId() != null) {
            customerMapper.updateById(customer);
        } else {
            customer.setStatus(CustomerStatusEnum.ON_ORDER.name());
            customerMapper.insert(customer);
        }
    }

    public Date getStartTime(String bookingRoom, Date startTime) {
        String time = DateFormatUtils.format(startTime, "yyyy-MM-dd");
        Date endDate = this.addDateDay(startTime, 1);
        String endTimes = DateFormatUtils.format(endDate, "yyyy-MM-dd");
        Date date = customerMapper.queryMaxEndTimeByRoom(bookingRoom, time,endTimes);
        if (date != null) {
            //将开席时间设置累加一小时
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            String value = DataLoader.getConfigValue("END_DURATION");
            calendar.add(Calendar.HOUR_OF_DAY, Integer.parseInt(value)); // 增加1个小时 注意加系统配置项里
            return calendar.getTime();
        } else {
            // 定义日期和时间的格式
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
//            DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//            String timeStr = "08:00";
//            // 将日期和时间字符串解析为LocalDateTime对象
//            LocalDateTime dateTime = LocalDateTime.parse(startTime + " " + timeStr, formatter);
//            // 转换为系统默认时区的ZonedDateTime
//            ZonedDateTime zonedDateTime = dateTime.atZone(ZoneId.systemDefault());
            Date endTime = this.getEndTime(startTime, 8);
            // 转换为Date对象
            return endTime;
        }
    }

    @Override
    public IPage<RCustomer> queryPageCustomerList(RCustomer customer, int current, int pageSize) {
        Page<RCustomer> page = new Page(current, pageSize);
        QueryWrapper<RCustomer> wrapper = new QueryWrapper();
        if (StringUtils.isNoneEmpty(customer.getName())) {
            wrapper.like(true, "name", customer.getName().trim());
        }
        if (StringUtils.isNotEmpty(customer.getPhone())) {
            wrapper.like(true, "phone", customer.getPhone().trim());
        }
        if (StringUtils.isNotEmpty(customer.getStatus())) {
            wrapper.eq(true, "status", customer.getStatus());
        }
        wrapper.orderBy(true, false, "create_time");
        return customerMapper.selectPage(page, wrapper);
    }

    @Override
    public List<RCustomer> queryOrderCustomerList(String status) {
        return customerMapper.queryOrderCustomerList(status);
    }

    /**
     * 根据ID查询客户信息
     *
     * @param createId
     * @return
     */
    @Override
    public RCustomer queryCustomerInfo(int createId) {
        return customerMapper.queryCustomerByCreateId(createId);
    }

    @Override
    public boolean validateCustomerPhoneExists(String phone) {
        int count = customerMapper.queryCustomerPhone(phone);
        return count > 0 ? false : true;
    }

    /**
     * 客户预约获取日期有些问题 ---之后记得更改
     *
     * @param startTime
     * @param mealDuration
     * @param bookingRoom
     * @return
     * @throws ParseException
     */
    @Override
    public Date queryEndTime(Date startTime, Integer mealDuration, String bookingRoom, Integer customerId) throws ParseException {
        /**
         * 查询预定客户数量
         */
        int count = customerMapper.queryBookingCustomerCount(customerId, CustomerStatusEnum.PLACE_ORDER.name(), bookingRoom, DateUtils.formatDate(startTime));
        Date sysDate = new Date();
        boolean result = DateUtils.compcompareToareTo(startTime, sysDate);
        if (customerId != null && count > 0) {
            return getEndTime(startTime, mealDuration);
        } else if (!result || count > 0) {
            return null;
        } else {
            return getEndTime(startTime, mealDuration);
        }
//        Date sysDate = new Date();
//        boolean result = DateUtils.compcompareToareTo(startTime, sysDate);
//        if (!result) {
//            return null;
//        } else if (date != null) {        // 使用Calendar类
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//            Calendar calendar = Calendar.getInstance();
//            calendar.setTime(sdf.parse(date));
//            calendar.add(Calendar.HOUR_OF_DAY, 2); // 增加两个小时
//            return DateUtils.compcompareToareTo(startTime, calendar.getTime()) ? getEndTime(startTime, mealDuration) : null;
//        } else {
//            return getEndTime(startTime, mealDuration);
//        }
    }

    @Override
    public void updateCustomerStatus(Integer id, String status) {
        RCustomer customer = new RCustomer();
        customer.setId(id);
        customer.setStatus(status);
        customerMapper.updateById(customer);
    }

    private Date getEndTime(Date startTime, Integer mealDuration) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startTime);
        calendar.add(Calendar.HOUR_OF_DAY, mealDuration); // 就餐时长
        // 获取新的时间
        return calendar.getTime();
    }
    private Date addDateDay(Date startTime, Integer mealDuration) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startTime);
        calendar.add(Calendar.DATE, mealDuration); // 就餐时长
        // 获取新的时间
        return calendar.getTime();
    }
    /**
     * 根据ID删除用户信息
     *
     * @param id
     * @return
     */
    @Override
    public void deleteCustomer(int id) {
        customerMapper.deleteById(id);
    }
}
